package com.scvtc.config.mybatisplus.update;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.scvtc.utils.SecurityUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DateTimeHandler implements MetaObjectHandler {

    private static final Logger log = LoggerFactory.getLogger(DateTimeHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = null;
        try {
            userId = SecurityUtil.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("com.yifei.config.mybatisplus.update.DateTimeHandler 发生错误 : {}", "账号插入");
            userId = -1L;
        }
        // 给 createTime 设置默认值
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = null;
        try {
            userId = SecurityUtil.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("com.yifei.config.mybatisplus.update.DateTimeHandler 发生错误 : {}", "账号修改");
            userId = -1L;
        }
        // 给 updateTime 设置默认值
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }
}